package com.llkj.qingnianguoxue.book;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.BookVideoAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.bean.BookVideoListBean;
import com.llkj.qingnianguoxue.bean.BuyVideoBean;
import com.llkj.qingnianguoxue.bean.EventChangeUserBean;
import com.llkj.qingnianguoxue.bean.response.ResponseList;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;
import com.sevenheaven.iosswitch.ShSwitchView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 订阅图书
 */
public class BookBooksFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    private static final int REQUEST_READ_BOOK_CODE = 6099;
    @BindView(R.id.sw_open)
    protected ShSwitchView mHideSwitch;//隐藏开关
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView lvActions;
    private BookVideoAdapter videoAdapter;
    private List<BookVideoListBean.CategoryBean> mVideosData;
    private int totalSize,mPage,mCurrentPosition;
    private String is_hide = "2";//是1 否2 隐藏已看完

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_book_books, container, false);
        ButterKnife.bind(this,rootView);
        EventBus.getDefault().register(this);
        initView();
        initListener();

        loadWaitDialog();
        onRefresh();
        return rootView;
    }

    private void initView() {
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.transparent);
        lvActions = (RecyclerView) rootView.findViewById(R.id.recyclerView);
//        GridLayoutManager gridLayoutManager =new GridLayoutManager(mActivity, 3);
        lvActions.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL,false));

        mVideosData = new ArrayList<>();
//        videoAdapter = new BookVideoAdapter(R.layout.item_book_video, mVideosData);
        videoAdapter = new BookVideoAdapter(R.layout.item_subscribe_video_book, mVideosData);
        videoAdapter.setType(2);
        lvActions.setAdapter(videoAdapter);
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(this);
        videoAdapter.setOnLoadMoreListener(this);
        mHideSwitch.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                if(isOn){
                    is_hide = "1";
                }else{
                    is_hide = "2";
                }
                onRefresh();
            }
        });
//        lvActions.addOnItemTouchListener(new OnItemClickListener() {
//            @Override
//            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
//                mCurrentPosition = i;
//                BookVideoListBean.BookVideoBean item = mVideosData.get(i);
////                Bundle bundle = new Bundle();
////                bundle.putString("id",item.getId());
////                bundle.putString("pdfUrl",item.getFile());
////                bundle.putString("bookName",item.getTitle());
////                bundle.putString("percent",item.getPlays_percent());
////                String page = StringUtils.isEmpty(item.getRead_page())?"0":item.getRead_page();
////                bundle.putString("readPage",page);
////                startActivityForResult(ReadBookActivity.class, bundle, REQUEST_READ_BOOK_CODE);
//                Intent intent = new Intent(getContext(), ReadActivity.class);
//                intent.putExtra("bookurl",item.getFile());
//                intent.putExtra("bookid",item.getId());
//                intent.putExtra("bookname",item.getTitle());
//                intent.putExtra("bookbegin",item.getRead_page());
//                startActivityForResult(intent,REQUEST_READ_BOOK_CODE);
//            }
//        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_OK){
            if(requestCode==REQUEST_READ_BOOK_CODE && data!=null){
//                BookVideoListBean.BookVideoBean item = mVideosData.get(mCurrentPosition);
//                item.setRead_page(data.getStringExtra("page"));
//                item.setPlays_percent(data.getStringExtra("percent"));
//                videoAdapter.notifyItemChanged(mCurrentPosition);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeUser(EventChangeUserBean event){
        onRefresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getVideoData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getVideoData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, videoAdapter, null, lvActions, totalSize);
    }

    private void getVideoData(){
        HttpMethod.userbuyBooks(getActivity(), this, is_hide, String.valueOf(mPage),"");
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_USER_USERBUY_BOOKS) {
            ResponseList<BuyVideoBean> hotRankingBean = GsonUtil.fromJsonList(data, BuyVideoBean.class);
            if (hotRankingBean != null) {
                try{
                    totalSize = Integer.parseInt(hotRankingBean.getNum());
                }catch (Exception e){}
                if (mPage == 1) {
                    mVideosData.clear();
                    LoadDataHelper.refreshComplete(videoAdapter, mVideosData, refreshLayout, lvActions);
                } else {
                    videoAdapter.setEnableLoadMore(true);
                    videoAdapter.loadMoreComplete();
                }
                videoAdapter.loadMoreEnd();
                List<BuyVideoBean> list = hotRankingBean.getBooks();
                if(list != null){
                    BuyVideoBean buyVideoBean = null;
                    BookVideoListBean.CategoryBean categoryBean = null;
                    for(int i=0;i<list.size();i++){
                        buyVideoBean = list.get(i);
                        boolean isHas = false;
                        for(int j=0;j<mVideosData.size();j++){
                            categoryBean = mVideosData.get(j);
                            if(buyVideoBean.getClassify().equals(categoryBean.getCategoryName())){
                                isHas = true;
                                break;
                            }
                        }
                        if(!isHas){
                            categoryBean = new BookVideoListBean.CategoryBean();
                            categoryBean.setCategoryName(buyVideoBean.getClassify());
                            mVideosData.add(categoryBean);
                        }
                        categoryBean.setCategoryList(buyVideoBean.getBooks());
                    }
                    videoAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        refreshLayout.setRefreshing(false);
    }
}
